438. 找到字符串中所有字母异位词
https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/
- 提交时间:2021-11-28 15:25:53
- 执行用时:36 ms, 在所有 Go 提交中击败了22.33%的用户
- 内存消耗:5.1 MB, 在所有 Go 提交中击败了31.55%的用户
- 通过测试用例:61 / 61
func findAnagrams(s string, p string) (ans []int) {
nP := len(p)
nS := len(s)
if nP > nS {
return []int{}
}
mapS, mapP := make(map[byte]int), make(map[byte]int)
for _, ch := range p {
mapP[byte(ch)]++
}
for i := 0; i < nP-1; i++ {
mapS[s[i]]++
}
for i := 0; i <= nS-nP; i++ {
mapS[s[i+nP-1]]++
if i > 0 {
mapS[s[i-1]]--
}
flag := true
for ch, countP := range mapP {
if countS, ok := mapS[ch]; !ok || countP != countS {
flag = false
break
}
}
if flag {
ans = append(ans, i)
}
}
return ans
}